import React, { useState, useEffect } from 'react';
import { PhotoProvider, PhotoConsumer } from 'react-photo-view';

import { NavBar, Icon, List, InputItem, Picker, DatePicker, TextareaItem, Button, Toast, Accordion, Modal, WhiteSpace } from 'antd-mobile';

import { logout as logoutOfTutor, GetTutorCheckCode as GetCheckCode, uploadPict, previewPict, postUpdatePhoto, postTutorUpdatePwd } from "@/api/login.js";

import { R, VOID } from "@/assets/js/dict"

import { GetTutorActionDetails } from '@/api/login.js'
import { updatePhoneOfTutor, getPhoneCodeForUpdatePhone } from "@/api/tutor/tutor";

import { createForm } from 'rc-form'

import header from "@/assets/svg/header.svg"
import './userInfo.scss';


const confirm = Modal.alert;

function UserInfo (props) {
    const [userInfoDetailsObject, setUserInfoDetailsObject] = useState({ pict: '', photo: '' })
    const [imgObject, SetImgObject] = useState({});
    const { getFieldProps } = props.form;
    const userInfo = JSON.parse(sessionStorage.getItem('userInfo'));
    let [hidden, setShow] = useState(false);
    let [hiddenPWD, setShowPWD] = useState(false);
    let [flush, setFlush] = useState("");

    /*刷新本页*/
    function doFlush () {
        setFlush(new Date().getTime());
    }

    // 去修改
    let handleToUpDate = () => {
        props.history.push({
            pathname: '/updataUserInfo',
            params: {
                'type': 'update',
                'id': userInfo.id
            }
        })
    };

    function getCheckCodeForUpdatePhone (call) {
        GetCheckCode().then(res => {
            if (R.isSuccess(res)) {
                console.log('res ----->>>', res)
                SetImgObject(R.getData(res));
                console.log('imgObject -------->>>', imgObject);
                if (!!call && typeof call === 'function') {
                    call();
                }
            }
        }).catch((err) => {
            console.log('err ----->>>', err)
        });
    }

    /**
     * 更新手机号
     */
    function updatePhone () {
        let formObj = props.form.getFieldsValue().Obj;
        console.log("f---> ", formObj);
        let phone = formObj.phone, code = formObj.phone_code;
        if (!!phone && !!code) {
            if (/^1[3-9]\d{9}$/.test(phone)) {
                updatePhoneOfTutor({ tutor_id: userInfo.id, new_phone: phone, code: code }, res => {
                    if (R.isSuccess(res)) {
                        Toast.success("操作成功！");
                        setShow(false);
                        doFlush();
                    }
                });
            } else {
                Toast.fail("请输入有效的手机号码", 3, VOID, true);
            }
        } else {
            Toast.show("请完善信息", 2, true);
        }
    }



    /**
     * 更新密码
     */
    function updatePwd () {
        let formObj = props.form.getFieldsValue().Obj;
        let oldPwd = formObj.oldPWD, newPwd = formObj.newPWD, repeatPwd = formObj.repeatPWD;
        if (!!oldPwd && !!newPwd && !!repeatPwd) {
            if (
                /^(?![A-Za-z]+$)(?![\\d]+$)(?![\\d\\W]+$)[a-zA-Z0-9\\W]{6,}$/.test(oldPwd)
                &&
                /^(?![A-Za-z]+$)(?![\\d]+$)(?![\\d\\W]+$)[a-zA-Z0-9\\W]{6,}$/.test(newPwd)
                &&
                /^(?![A-Za-z]+$)(?![\\d]+$)(?![\\d\\W]+$)[a-zA-Z0-9\\W]{6,}$/.test(repeatPwd)
            ) {
                if (newPwd === repeatPwd) {
                    postTutorUpdatePwd({ id: userInfo.id, oldPwd, newPwd }, res => {
                        if (R.isSuccess(res)) {
                            Toast.success("操作成功！");
                            setShowPWD(false);
                            doFlush();
                        }
                    });
                } else {
                    Toast.fail("新密码与重复密码不一致", 3, VOID, true);
                }
            } else {
                Modal.alert('提示', '请输入有效的密码, 内容包含大小写字母和数字，长度不少于6位', [
                    { text: '确认' },
                ])
            }
        } else {
            Toast.show("请完善信息", 2, true);
        }
    }


    /**
     * 唤起修改手机的模态框
     */
    function updatePhoneModal () {

        confirm('修改手机号码', '确定要修改手机号码吗？', [
            {
                text: '取消', onPress: () => {

                }
            }, {
                text: '确定', onPress: () => {
                    getCheckCodeForUpdatePhone(() => setShow(true));
                }
            }]);
    }

    /**
     * 唤起修改密码的模态框
     */
    function updatePwdModal () {
        confirm('修改密码', '确定要修改密码吗？', [
            {
                text: '取消', onPress: () => {

                }
            }, {
                text: '确定', onPress: () => {
                    setShowPWD(true)
                }
            }]);
    }

    /*
    * 发送手机验证码
    * */
    function send () {
        let postData = {};
        let formObj = props.form.getFieldsValue().Obj;
        let phone = formObj.phone, pict_code = formObj.pict_code;
        if (!!phone) {
            if (/^1[3-9]\d{9}$/.test(phone)) {
                getPhoneCodeForUpdatePhone({ flag: imgObject.key, pict_code: pict_code, new_phone: phone, id: userInfo.id }, res => {
                    if (R.isSuccess(res)) {
                        Toast.success("发送成功，请注意查收短信", 2, VOID, true)
                    }
                });
            } else {
                Toast.fail("请输入有效的手机号码", 3, VOID, true);
            }
        } else {
            Toast.info("请填写手机号码", 2);
            return;
        }

        postData.flag = imgObject.key;
        if (!!pict_code) {
            postData.code = formObj.pict_code;
        } else {
            Toast.info("请填写图形验证码", 2);
        }
    }

    useEffect(() => {
        // 查看家教详细信息
        let postData = {};
        postData.tutor_id = JSON.parse(sessionStorage.getItem('userInfo')).id; // 家教ID 

        GetTutorActionDetails(postData).then(res => {
            if (res.code == '000000') {
                console.log('res -------->>>', res);
                setUserInfoDetailsObject(res.responseData)
            }
        }).catch(err => {

        })
    }, [flush])

    return (
        <div className="user-info">
            <div className="page-title  student-tit">
                <NavBar
                    mode="light"
                    icon={<Icon type="left" />}
                    onLeftClick={() => {
                        props.history.push({
                            pathname: '/mainTutor',
                            query: {
                                selectedTab: 'my'
                            }
                        })
                    }}
                    rightContent={[
                        <span key={"edit"} onClick={handleToUpDate}>编辑</span>,
                    ]}
                >
                    个人信息
                </NavBar>

            </div>
            <div className="page-content student-content">
                <div className="student-content-piece">
                    <div className="form-box">
                        <div className="form-tit">
                            <i className="mini-block" />
                            <strong>基本信息</strong>
                        </div>
                        <div className="form-con">
                            <List>
                                <List.Item extra={userInfoDetailsObject.name}>姓名</List.Item>
                                <List.Item extra={userInfoDetailsObject.gender}>性别</List.Item>
                                <List.Item extra={userInfoDetailsObject.phone}>联系方式</List.Item>
                            </List>
                        </div>

                        <div className="form-tit">
                            <i className="mini-block" />
                            <strong>教育信息</strong>
                        </div>
                        <div className="form-con">
                            <List>
                                <List.Item extra={userInfoDetailsObject.school}>学校</List.Item>
                                <List.Item extra={userInfoDetailsObject.code}>学号</List.Item>
                                <List.Item extra={
                                    <div>
                                        {
                                            userInfoDetailsObject.pict ?
                                                <PhotoProvider>
                                                    {
                                                        (userInfoDetailsObject.pict).split(',').map((item, index) => {
                                                            if (item != "") {
                                                                return <PhotoConsumer key={index} src={previewPict(item)} intro={''}>
                                                                    <img
                                                                        key={item}
                                                                        style={{
                                                                            width: 'auto',
                                                                            height: 'auto',
                                                                            maxHeight: '70px',
                                                                            maxWidth: '100px',
                                                                            margin: '0 5px'
                                                                        }} src={previewPict(item)}
                                                                        alt={"学生证信息"}
                                                                    />
                                                                </PhotoConsumer>
                                                            }
                                                        })
                                                    }
                                                </PhotoProvider>
                                                :
                                                ''
                                        }
                                    </div>

                                }
                                >学生证信息</List.Item>
                                <List.Item extra={
                                    <div>
                                        {
                                            userInfoDetailsObject.photo ?
                                                <PhotoProvider>
                                                    {
                                                        (userInfoDetailsObject.photo).split(',').map((item, index) => {
                                                            if (item != "") {
                                                                return <PhotoConsumer key={index} src={previewPict(item)} intro={''}>
                                                                    <img
                                                                        key={item}
                                                                        style={{
                                                                            width: 'auto',
                                                                            height: 'auto',
                                                                            maxHeight: '70px',
                                                                            maxWidth: '100px',
                                                                            margin: '0 5px'
                                                                        }} src={previewPict(item)}
                                                                        alt={"头像"}
                                                                    />
                                                                </PhotoConsumer>
                                                            }
                                                        })
                                                    }
                                                </PhotoProvider>
                                                :
                                                <PhotoProvider>
                                                    <PhotoConsumer key={'header'} src={header} intro={''}>
                                                        <img src={header} />
                                                    </PhotoConsumer>
                                                </PhotoProvider>
                                        }
                                    </div>

                                }
                                >头像</List.Item>
                            </List>
                        </div>
                        <div className="form-tit">
                            <i className="mini-block" />
                            <strong>其他信息</strong>
                        </div>
                        <div className="form-con">
                            <List>
                                <List.Item extra={userInfoDetailsObject.pass_test ? '是' : '否'}>是否通过测评</List.Item>
                            </List>

                        </div>
                    </div>
                    <div className="btns">
                        <Button type="primary" onClick={updatePhoneModal}>修改手机号码</Button>
                        <WhiteSpace size="lg" />
                        <Button type="primary" onClick={updatePwdModal}>修改密码</Button>
                    </div>
                </div>
            </div>

            {/* 修改手机号码 */}
            <Modal
                visible={hidden}
                popup
                animationType="slide-up"
                maskClosable
                title={<h4 style={{ paddingTop: '11px' }}><strong>修改手机号码</strong></h4>}
                footer={[{
                    style: {
                        color: '#fff',
                        border: '1PX solid #e94f4f',
                        borderRadius: '5PX',
                        backgroundColor: '#e94f4f'
                    },
                    text: '取消', onPress: () => {
                        setShow(false);
                    }
                }, {
                    style: {
                        color: '#fff',
                        border: '1PX solid #108ee9',
                        borderRadius: '5PX',
                        backgroundColor: '#108ee9'
                    },
                    text: '确定', onPress: updatePhone
                }]}

            >
                <div style={{ height: "34vh", overflow: 'scroll', width: 'auto' }}>
                    <List>
                        <InputItem {...getFieldProps("Obj.phone", { initialValue: "" })} placeholder="请输入新手机号码">新手机号码</InputItem>
                        <InputItem {...getFieldProps("Obj.pict_code", { initialValue: "" })} placeholder="请输入图形验证码"
                            type="digit" extra={<img style={{
                                width: '90px',
                                height: 'auto',

                                marginLeft: '10px'
                            }} src={'data:image/png;base64,' + imgObject.img} onClick={getCheckCodeForUpdatePhone}
                            />}
                        >图形验证码</InputItem>

                        <InputItem {...getFieldProps("Obj.phone_code", { initialValue: "" })} placeholder="请输入短信验证码"
                            type="digit" extra={<Button type={"primary"} size="small"
                                style={{ textAlign: 'center', top: '0', bottom: '0' }}
                                onClick={send}
                            >{'发送'}</Button>}

                        >短信验证码</InputItem>
                    </List>
                </div>
            </Modal>



            {/* 修改密码 */}
            <Modal
                visible={hiddenPWD}
                popup
                animationType="slide-up"
                maskClosable
                title={<h4 style={{ paddingTop: '11px' }}><strong>修改密码</strong></h4>}
                footer={[{
                    style: {
                        color: '#fff',
                        border: '1PX solid #e94f4f',
                        borderRadius: '5PX',
                        backgroundColor: '#e94f4f'
                    },
                    text: '取消', onPress: () => {
                        setShowPWD(false);
                    }
                }, {
                    style: {
                        color: '#fff',
                        border: '1PX solid #108ee9',
                        borderRadius: '5PX',
                        backgroundColor: '#108ee9'
                    },
                    text: '确定', onPress: updatePwd
                }]}

            >
                <div style={{ height: '34vh', overflow: 'scroll', width: 'auto' }}>
                    <List>
                        <InputItem placeholder="请输入有效的密码, 内容包含大小写字母和数字，长度不少于6位" {...getFieldProps("Obj.oldPWD", { initialValue: "" })} type="password">旧密码</InputItem>
                        <InputItem placeholder="请输入有效的密码, 内容包含大小写字母和数字，长度不少于6位" {...getFieldProps("Obj.newPWD", { initialValue: "" })} type="password">新密码</InputItem>
                        <InputItem placeholder="请重复密码" {...getFieldProps("Obj.repeatPWD", { initialValue: "" })} type="password">重复密码</InputItem>
                    </List>
                </div>
            </Modal>
        </div >
    );
}


UserInfo = createForm()(UserInfo);

export default UserInfo;